//
//  YHGroupListViewController.m
//  YHChatProject
//
//  Created by erpapa on 16/5/1.
//  Copyright © 2016年 erpapa. All rights reserved.
//

#import <CoreData/CoreData.h>
#import "YHGroupListViewController.h"
#import "HYGroupChatVC.h"
#import "HYXMPPGroupManager.h"
#import "HYContactsModel.h"
#import "YHGroupListViewCell.h"
#import "XMPPRoom.h"
#import "HYUtils.h"
#import "YHGroupSearchListController.h"
#import "HYSearchController.h"
#import "HYAddFriendViewController.h"
#import "HYRecentChatViewController.h"
#import "YHGroupInviteViewController.h"

@interface YHGroupListViewController ()<UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic, strong) HYSearchController *searchController;
@property (nonatomic, strong) YHGroupSearchListController *resultsController;

@end

@implementation YHGroupListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"群聊";
    self.view.backgroundColor = [UIColor whiteColor];
    // 搜索
    self.resultsController = [[YHGroupSearchListController alloc] init];
    self.searchController = [[HYSearchController alloc] initWithSearchResultsController:self.resultsController];
    self.searchController.searchResultsUpdater = self;
    self.searchController.delegate = self;
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.delegate = self; // so we can monitor text changes + others
    self.definesPresentationContext = YES;// know where you want UISearchController to be displayed
    self.tableView.tableHeaderView = self.searchController.searchBar;
    [self.view addSubview:self.tableView];
    
    // 创建/添加房间
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(createRoom:)];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 获得房间列表
    [self loadBookmarkedRooms];

}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.searchController.active = NO; // 当view消失后取消搜索的激活状态
}

#pragma mark - 更新搜索结果 UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSMutableArray *searchResults = [NSMutableArray array];
    [self.dataSource enumerateObjectsUsingBlock:^(HYContactsModel *model, NSUInteger idx, BOOL *stop) {
        if ([model.jid.user.uppercaseString containsString:self.searchController.searchBar.text.uppercaseString]) {
            [searchResults addObject:model];
        }
    }];
    YHGroupSearchListController *tableController = (YHGroupSearchListController *)self.searchController.searchResultsController;
    tableController.searchResults = searchResults;//传递搜索结果
    [tableController.tableView reloadData];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}


#pragma mark - UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YHGroupListViewCell *cell = [YHGroupListViewCell cellWithTableView:tableView];
    HYContactsModel *model = [self.dataSource objectAtIndex:indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYGroupChatVC *groupChat = [[HYGroupChatVC alloc] init];
    HYContactsModel *model = [self.dataSource objectAtIndex:indexPath.row];
    groupChat.model = model;
    groupChat.hidesBottomBarWhenPushed = YES;
    UIViewController *firstVC = [self.navigationController.viewControllers firstObject]; // 第一个
//    if ([firstVC isKindOfClass:[HYRecentChatViewController class]]) {
        [self.navigationController setViewControllers:@[firstVC,groupChat] animated:YES];
//    }else{
//        [self.navigationController pushViewController:groupChat animated:YES];
//    }
}

#pragma mark - 创建/加入房间
- (void)createRoom:(id)sender
{
    HYAddFriendViewController *addFriendVC = [[HYAddFriendViewController alloc] init];
    addFriendVC.type = HYAddFriendTypeCreateGroup;
    [self.navigationController pushViewController:addFriendVC animated:YES];
    
//    YHGroupInviteViewController *inviteVC = [[YHGroupInviteViewController alloc] init];
//    [self.navigationController pushViewController:inviteVC animated:YES];
}

- (void)loadBookmarkedRooms
{
    // 获取数据
    NSArray *bookmarkedGroups = [HYXMPPGroupManager sharedInstance].bookmarkedGroups;
    
    if (bookmarkedGroups.count > 0) {
        
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:bookmarkedGroups];
        [self.tableView reloadData];
    }
    [self queryMyGroups];
}

#pragma mark - 懒加载

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = kGroupListViewCellHeight;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

// 懒加载
- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)queryMyGroups
{
//    [HYUtils showWaitingMsg:@"加载中.."];
    YHWeakifySelf;
    [[HYXMPPGroupManager sharedInstance] queryMyGroupsWithSuccess:^(NSArray *bookmarkedGroups) {
        if (bookmarkedGroups.count == 0 && yh_weak_self.dataSource.count == 0) {
            [HYUtils alertWithNormalMsg:@"您暂未加入群聊！"];
        }else{
            [HYUtils clearWaitingMsg];
            [yh_weak_self.dataSource removeAllObjects];
            [yh_weak_self.dataSource addObjectsFromArray:bookmarkedGroups];
            [yh_weak_self.tableView reloadData];
        }
    }];
}


@end
